//
//  UIColor+addition.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/12.
//  Copyright © 2018年 imf. All rights reserved.
//

import Foundation
import UIKit

extension UIColor {
    
    /**
     *
     *  十六进制加透明度
     *
     *  @param hexString 颜色的十六进制
     *  @param alpha     透明度
     *
     *  @return 返回UIColor
     */
    class func colorFromHexString(hexString: String, alpha: CGFloat) -> UIColor {
        var rgbValue: UInt64 = 0;
        var hexString = hexString
        hexString = hexString.replacingOccurrences(of: "#", with: "")
        let scanner = Scanner(string: hexString)
        scanner.scanLocation = 0
        scanner.scanHexInt64(&rgbValue)

        let r = (CGFloat)((rgbValue & 0xff0000) >> 16)
        let g = (CGFloat)((rgbValue & 0xff00) >> 8)
        let b = (CGFloat)(rgbValue & 0xff)
        
        return UIColor.color(red: r, green: g, blue: b, alpha: alpha)
    }
    
    
    /**
     *
     *  十六进制,6位长度不包含透明度，8位前2位是透明度，后面是颜色值
     *
     *  @param hexString 颜色的十六进制，如“#ffffff”或者#FFFFFFF
     *
     *  @return 返回UIColor类型
     */
    class func colorFromHexString(hexString: String) -> UIColor {
        
        var hexString = hexString
        hexString = hexString.replacingOccurrences(of: "#", with: "")
        if (hexString.count == 6) {
            return self.colorFromHexString(hexString: hexString, alpha: 1.0)
        } else {
            var rgbValue: UInt64 = 0;
            let scanner = Scanner(string: hexString)
            scanner.scanLocation = 0
            scanner.scanHexInt64(&rgbValue)

            let r = (CGFloat)((rgbValue & 0xff0000) >> 16)
            let g = (CGFloat)((rgbValue & 0xff00) >> 8)
            let b = (CGFloat)(rgbValue & 0xff)
            
            return UIColor.color(red: r, green: g, blue: b, alpha: (CGFloat((rgbValue & 0xFF000000) >> 24)) / 255.0)
        }
    }
    
    
    /**
     *
     *  通过传入的值装换成颜色，比如255,255,255,1
     *
     *  @param red   红色取值范围[0,255]
     *  @param green 绿色取值范围[0,255]
     *  @param blue 蓝色取值范围[0,255]
     *  @param alpha 透明度取值范围[0,1]
     *
     *  @return 返回UIColor类型
     */
    class func color(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
        return UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha)
    }
    
}
